#!/usr/bin/python
# -*- coding: utf-8 -*-

import string
from class_segment import *
import tool_maths

def is_inside(o,e,o1,e1) :
  return (o1 >= o and e1 <= e)

def is_encaps(o,e,o1,e1) :
  return (o1 <= o and e1 >= e)

def reader_seg2seg_inside(id_bloc,o,l,mysql_cursor) :
  e = o + l - 1
  req  = 'SELECT r.id_rstr, r.id_graphie, r.offset, g.graphie, g.len '
  req += 'FROM `Rstr` r, `Graphie` g '
  req += 'WHERE r.id_bloc = \'%s\' '%(id_bloc)
  req += '  AND g.id_graphie = r.id_graphie '
  req += '  AND (r.offset <= %i AND (r.offset + g.len -1) >= %i);'%(e,o)
  mysql_cursor.execute(req)


def lg2relative_id_doc(lg, mysql_cursor) :
  req  = 'SELECT d.id_document '
  req += 'FROM `Document` d '
  req += 'WHERE d.lg=\'%s\';'%(lg)

  mysql_cursor.execute(req)

  corres = {} 
  cpt = 0
  for ligne in mysql_cursor :
    cpt += 1
    corres[ligne[0]] = cpt

  return corres

def lg2relative_id_bloc(lg, mysql_cursor) :
  req  = 'SELECT b.id_bloc '
  req += 'FROM `Bloc` b,`Document` d '
  req += 'WHERE b.id_document=d.id_document'
  req += '   AND d.lg="' + lg + '";'

  mysql_cursor.execute(req)

  corres = {} 
  cpt = 0
  for ligne in mysql_cursor :
    cpt += 1
    corres[ligne[0]] = cpt

  return corres

def reader_id_document2array(id_document, mysql_cursor) :
  req  = ' SELECT b.id_bloc,b.contenu_text'
  req += ' FROM `Document` d, `Bloc` b'
  req += ' WHERE d.id_document=%i'%(id_document)
  req += '   AND d.id_document=b.id_document;';
  mysql_cursor.execute(req)

def reader_id_bloc2info_chunk(id_bloc,mysql_cursor) :
  req  = 'SELECT c.id_chunk, r.id_word, r.offset, g.len, g.graphie, c.type '
  req += 'FROM `Word` r, `Graphie` g, `Chunk` c '
  req += 'WHERE r.id_bloc=' + str(id_bloc) + ' '
  req += '  AND r.id_word = c.id_word AND g.id_graphie = r.id_graphie '
  req += 'ORDER BY c.id_chunk,r.offset;'
  mysql_cursor.execute(req)
  
  chunk = {}
  last_id_chunk = -1

  for ligne in mysql_cursor :
    mot = [ligne[1], ligne[2], ligne[3], ligne[4], ligne[5]]
    if last_id_chunk < 0 :
      last_id_chunk = ligne[0]
      chunk[ligne[0]] = []
    if(ligne[0] == last_id_chunk) :
      chunk[ligne[0]].append(mot)
    else :
      chunk[ligne[0]] = [mot]
    last_id_chunk = ligne[0];

  return chunk;

def lg_graphie2repartition_bloc(lg,graphie,array_corres,mysql_cursor) :
  req = """
    SELECT r.id_graphie,r.id_bloc,COUNT(r.id_bloc)
    FROM `Rstr` r,`Bloc` b, `Document` d, `Graphie` g
    WHERE r.id_bloc = b.id_bloc
      AND b.id_document = d.id_document
      AND d.lg = %s
      AND r.id_graphie = g.id_graphie
      AND g.graphie = %s
    GROUP BY r.id_bloc,r.id_graphie
    ORDER BY r.id_graphie,r.id_bloc
  ;"""

  mysql_cursor.execute(req,(lg,graphie))
  rep = {}
  for ligne in mysql_cursor :
    relative_id_bloc = array_corres[ligne[1]]
    rep[relative_id_bloc] = ligne[2]

  return rep


def bc2ac(v,txt) :
  ac = []
  for j,array_mot in v.iteritems() :
    am = []
    for mot in array_mot :
      attr = {'type':mot[4]}
      am.append(Mot(txt,mot[1],mot[2],attr))
    am.sort()
    ac.append(Chunk(am))
  ac.sort()
  return ac

def chunk2rstr_info(ac,id_bloc,mysql_cursor) :
  res = {}
  for i,c_src in enumerate(ac) :
    o_src = c_src.get_offset()
    l_src = c_src.get_len()
    e_src = l_src + o_src
    reader_seg2seg_inside(id_bloc,o_src,l_src,mysql_cursor)
    inside = []
    union = []
    outside = []
#    print candidats
    for c in mysql_cursor :
      c_end = c[2] + c[4]
      if (is_inside(o_src, e_src, c[2], c_end)) :
        inside.append(c)
      elif (is_encaps(o_src, e_src, c[2], c_end)) :
        inside.append(c)
      else :
        outside.append(c)
    res[i] = {'outside' : outside, 'inside' : inside}
  return res  


#pour un chunk donné, renvoies les rstr_max rattachées (in ET out)

def chunk2rstr(ac,id_bloc,mysql_cursor) :
  res = {}
  for i,c_src in enumerate(ac) :
    o_src = c_src.get_offset()
    l_src = c_src.get_len()
    reader_seg2seg_inside(id_bloc,o_src,l_src,mysql_cursor)
    res[i] = []
    for c in mysql_cursor :
      res[i].append(c)
  return res  


#pour un chunk donné, renvoies les rstr_max rattachées (in ET out)
#filtrées par longueur

def rstr_filter_len(rstr) :
  rstr_filtre = rstr.replace(" ","")
  rstr_unicode = unicode(rstr_filtre,"utf-8")
  return len(rstr_unicode)

def rstr_normal_len(rstr) :
  rstr_unicode = unicode(rstr,"utf-8")
  return len(rstr_unicode)

def rstr_strip_len(rstr) :
  rstr_unicode = unicode(rstr,"utf-8")
  rstr_unicode = rstr_unicode.strip()
  return len(rstr_unicode)

#signe d'un problème dans l'injection des str dans la BD :
def filter_doublon(l) :
  s = set()
  nl = []
  for item in l :
    nitem = (item[2],item[4])
    if(nitem not in s) :
      s.add(nitem)
      nl.append(item)
  return nl

def chunk2rstr_filtered(ac,id_bloc,conn) :
  res = {}
  for i,c_src in enumerate(ac) :
    o_src = c_src.get_offset()
    l_src = c_src.get_len()
    e_src = l_src + o_src - 1
    mysql_cursor = conn.cursor()
    reader_seg2seg_inside(id_bloc,o_src,l_src,mysql_cursor)
    r = []
#    print c_src, o_src, e_src
    
    for c in mysql_cursor :
      o_c = c[2]
      e_c = c[2] + c[4] - 1
      filter_len = rstr_filter_len(c[3])
      normal_len = rstr_normal_len(c[3])
      strip_len = rstr_strip_len(c[3])
      if(normal_len < 3) :
        continue
      if(False) :
        r.append(c)
      elif tool_maths.is_in(o_c,e_c,o_src,e_src) :
#        print "0",c[3]
        r.append(c)
      elif tool_maths.is_in(o_src,e_src,o_c,e_c) :
        if(strip_len == normal_len - 2) :
          r.append(c)
#          print "1",c[3]
        
        if(strip_len == normal_len - 1) :
          if(strip_len > 2) :
            r.append(c)
#          print "2",c[3],

        elif(filter_len == normal_len) :
          if(normal_len >= 5) :
            r.append(c)
#            print "3",c[3]
          else :
            pass
#            print "2.",c[3], c[2], c[4]

        elif(float(filter_len) / float(normal_len) >= (3./5.)) :
          r.append(c)
#          print "4",c[3],filter_len,normal_len,5/6
        else :
          pass
#          print "3.",c[3], c[2], c[4]
#      else :
#        pass
#
#      if(True) :
#        pass

      elif tool_maths.is_overlap(o_src,e_src,o_c,e_c) :
#        print "2",c[3]
        inter_len = tool_maths.len_interval_inter(o_src,e_src,o_c,e_c)

        if(inter_len > 3) :
          if(float(filter_len) / float(normal_len) >= (3./5.)) :
            r.append(c)
        else :
#          print "4.",c[3], c[2], c[4]
          pass
    new_r = filter_doublon(r)
#    for i in new_r :
#      print "  ",i[3], i[2], i[4]
#    for i in r :
#      print i[3]
#    1/0
#    res[i] = r
    res[i] = new_r
  return res  
